package com.zhsource.system.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhsource.system.domain.Course;
import com.zhsource.system.mapper.CourseMapper;
import com.zhsource.system.query.CourseQuery;
import com.zhsource.system.service.ICourseService;
import com.zhsource.utils.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.List;

@Service
public class CourseServiceImpl implements ICourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public List<Course> list() {
        return courseMapper.list();
    }

    @Override
    public Course selectById(Long id) {
        return courseMapper.selectById(id);
    }

    @Override
    public PageInfo<Course> page(CourseQuery courseQuery) {
        // // 1.查询总条数
        // Integer total = courseMapper.total(courseQuery);
        // // 2.查询当前页数据
        // List<Course> page = courseMapper.page(courseQuery);
        // return new PageResult<>(total, page);

        // 1.下面这句代码表示开启分页，会将紧挨着这句代码的下一次数据库执行进行分页，切记一定要放在要分页的SQL语句前面执行
        PageHelper.startPage(courseQuery.getCurrentPage(), courseQuery.getPageSize());

        // 2.执行SQL语句带条件查询，SQL语句不需要进行分页
        List<Course> courses = courseMapper.page(courseQuery);

        // 3.将查询结果转换为PageInfo对象，PageInfo对象中有前端分页所需要的各种参数
        PageInfo<Course> pageInfo = new PageInfo<>(courses);

        // 4.响应总条数和分页信息
        return pageInfo;
    }

    @Override
    public void insert(Course course) {
        // 1、新增课表信息
        courseMapper.insert(course);
    }

    @Override
    public void update(Course course) {
        // 1、修改课表数据
        courseMapper.update(course);
    }

    @Override
    public void delete(Long id) {
        courseMapper.delete(id);
    }

    @Override
    public void batchDel(List<Long> ids) {
        courseMapper.batchDel(ids);
    }

    @Override
    public List<Course> getAll() {
        return courseMapper.getAll();
    }

    @Override
    public void importExcel(MultipartFile file) {
        try {
            // 1.使用工具类从复杂文件中获取到课表信息集合
            List<Course> courses = ExcelUtil.importExcel(file, Course.class);
            // 2.调用批量新增方法，保存所有课表信息
            courseMapper.batchAdd(courses);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
